<?php
/**
 * Created by PhpStorm.
 * User: Egg
 * Date: 2018/4/11
 * Time: 9:13
 */

namespace Admin\Controller;


use Admin\Model\ImageResourceLogic;
use Admin\Model\WxResourceLogic;
use Think\Controller;
use Think\Exception;

class WxResApiController extends Controller
{

    /**
     * 获取微信素材列表
     */
    public function get_wx_res_list()
    {
        //根据不同类型选择数据库
        $type = I('type');
        switch ($type) {
            case 'image': {
                $model = D('Admin/ImageResource')
                    ->alias('m')
                    ->join('inner join wx_attachment as a on m.media_id = a.media_id');
            }
                break;
            case 'voice': {
                $model = D('Admin/VoiceResource')
                    ->alias('m')
                    ->join('inner join wx_attachment as a on m.media_id = a.media_id');
            }
                break;
            case 'video': {
                $model = D('Admin/VideoResource')
                    ->alias('m')
                    ->join('inner join wx_attachment as a on m.media_id = a.media_id');
            }
                break;
            default: {
                \Common\Common\request_parameter_invalid();
                exit;
            }
        }
        $data['wx_res'] = $model
            ->page(I('page'), 15)
            ->order('m.update_time desc')
            ->field(array(
                'm.id',
                'm.update_time',
                'm.media_id',
                'a.tag' => 'url',
                'a.filename' => 'name'
            ))->select();
        $data['max_page'] = ceil($model->count() / 15);

        \Common\Common\print_json_data(200, $data, '查询成功');
    }

    /**
     * 更新微信素材列表
     */
    public function update_wx_res()
    {
        //根据不同类型选择数据库
        $type = I('type');
        switch ($type) {
            case 'image': {
                $model = D('Admin/ImageResource');
            }
                break;
            case 'voice': {
                $model = D('Admin/VoiceResource');
            }
                break;
            case 'video': {
                $model = D('Admin/VideoResource');
            }
                break;
            default: {
                \Common\Common\request_parameter_invalid();
                exit;
            }
        }

        $logic = new WxResourceLogic();
        $model->startTrans();
        try {
            $new_data = $logic->get_wx_res($type);
            foreach ($new_data as $item) {
                //判断数据库已经是否存在数据
                $media_id = $item['media_id'];
                if ($logic->is_exit($media_id, $model)) {
                    continue;
                } else {
                    $model->add($item);
                }
            }
        } catch (Exception $exception) {
            $model->rollback();
            echo $exception->getMessage();
        }
        $model->commit();

        \Common\Common\print_json_data(200, '', '拉取成功');
    }


}